"""
思和智库 - FastAPI 主应用
ShiheTech KnowledgeHub Backend Application

Version: 2.1.0
Port: 3301
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
import logging
from loguru import logger

from app.core.config import settings
from app.models.database import check_db_connection
from app.middleware.error_handler import setup_error_handlers
from app.middleware.performance_monitor import PerformanceMonitorMiddleware
from app.utils.logging_utils import setup_logging, SensitiveDataFilter

# 配置日志（带敏感数据过滤）
setup_logging(settings.LOG_LEVEL)

logger.add(
    f"{settings.LOG_DIR}/app.log",
    rotation=settings.LOG_ROTATION,
    retention=settings.LOG_RETENTION,
    level=settings.LOG_LEVEL,
    format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {name}:{function}:{line} - {message}",
    encoding="utf-8",
    filter=lambda record: SensitiveDataFilter().filter(record)
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理
    启动和关闭时执行的操作
    """
    # 启动时
    logger.info("=" * 60)
    logger.info(f"🚀 {settings.APP_NAME} v{settings.APP_VERSION} 正在启动...")
    logger.info(f"📝 环境: {settings.ENVIRONMENT}")
    logger.info(f"🌐 监听地址: {settings.HOST}:{settings.PORT}")
    logger.info("=" * 60)
    
    # 检查数据库连接
    if check_db_connection():
        logger.info("✅ 数据库连接正常")
    else:
        logger.error("❌ 数据库连接失败！")
    
    logger.info(f"✅ {settings.APP_NAME} 启动完成！")
    logger.info(f"📚 API 文档: http://{settings.HOST}:{settings.PORT}/docs")
    
    yield
    
    # 关闭时
    logger.info(f"👋 {settings.APP_NAME} 正在关闭...")


# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    description="汇聚智慧，赋能政企 - 智能知识管理系统",
    version=settings.APP_VERSION,
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# 配置CORS - 必须在路由之前添加
logger.info(f"配置CORS允许的源: {settings.CORS_ORIGINS}")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 临时允许所有源，用于调试
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加性能监控中间件
app.add_middleware(PerformanceMonitorMiddleware, slow_threshold=1.0, very_slow_threshold=5.0)
logger.info("✅ 性能监控中间件已启用")

# 配置全局错误处理器
setup_error_handlers(app)


# ==================== 根路由 ====================
@app.get("/")
async def root():
    """根路径，返回系统信息"""
    return {
        "name": settings.APP_NAME,
        "version": settings.APP_VERSION,
        "slogan": "汇聚智慧，赋能政企",
        "status": "running",
        "docs": f"http://{settings.HOST}:{settings.PORT}/docs"
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    db_status = check_db_connection()
    
    return {
        "status": "healthy" if db_status else "unhealthy",
        "database": "connected" if db_status else "disconnected",
        "version": settings.APP_VERSION
    }


# ==================== API 路由 ====================
from app.api import api_router

app.include_router(api_router)

# 将在后续步骤中添加更多模块的路由:
# - users (用户管理)
# - documents (文档管理)
# - categories (分类管理)
# - knowledge_base (知识库)
# - chat (RAG问答)
# - models (模型配置)


# ==================== 异常处理 ====================
# 全局异常处理已由 setup_error_handlers(app) 配置


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app.main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.RELOAD
    )

